<template>
  <div class="app-container">
    <el-row>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handlerCreate"
      >
        {{ $t("table.add") }}
      </el-button>
    </el-row>
    <el-row>
      <el-table
        :data="treeData"
        style="width: 100%; margin-top: 5px"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="url" label="URL"> </el-table-column>
        <el-table-column label="必选">
          <template slot-scope="{ row }">
            <i v-if="row.required" class="el-icon-check" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="日期"> </el-table-column>
        <el-table-column
          :label="$t('table.actions')"
          align="center"
          width="230"
          class-name="fixed-width"
        >
          <template slot-scope="{ row }">
            <el-button
              icon="el-icon-edit"
              @click="handlModify(row)"
              circle
            ></el-button>
            <el-button
              icon="el-icon-delete"
              @click="hanlderDestory(row)"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-dialog title="编辑系统资源" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tmpPermissionModel"
        :close-on-click-modal="false"
        label-position="left"
        label-width="100px"
        style="width: auto; margin-left: 50px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="tmpPermissionModel.name" />
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="tmpPermissionModel.url" />
        </el-form-item>

        <el-form-item label="分组名称" prop="grp">
          <el-select
            v-model="tmpPermissionModel.grp"
            filterable
            allow-create
            default-first-option
            placeholder="请选择分组名称"
          >
            <el-option
              v-for="item in grpLs"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <span style="margin-left: 10px">（可添加）</span>
        </el-form-item>
        <el-form-item label="必选" prop="required">
          <el-checkbox v-model="tmpPermissionModel.required"
            >（每个人都有的权限）</el-checkbox
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="editData">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import {
  compayLs,
  saveCompany,
  destoryCompany,
  sysPermission,
  savePermission,
  destoryPermission,
} from "@/api/users";
import { parseTime } from "@/utils";
import { cloneDeep } from "lodash";
import { Form } from "element-ui";
@Component({
  name: "SysPermission",
})
export default class extends Vue {
  mounted() {
    this.loadSysPermission();
  }
  private dialogFormVisible = false;

  private tmpPermissionModel = {};
  private defaultPermissionValue = {
    createTime: parseTime(new Date()),
    updateTime: parseTime(new Date()),
    name: "",
    url: "",
    grp: "",
    required: false,
  };
  private handlerCreate() {
    this.dialogFormVisible = true;
    this.tmpPermissionModel = cloneDeep(this.defaultPermissionValue);
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }

  private handlModify(row: any) {
    this.dialogFormVisible = true;
    this.tmpPermissionModel = cloneDeep(row);
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }
  private hanlderDestory(row: any) {
    this.$confirm("删除将不可恢复，您确定要删除吗？").then(async (val: any) => {
      let d = await destoryPermission([row.id]);
      this.loadSysPermission();
      this.$message({
        message: "删除成功",
        type: "success",
      });
    });
  }

  private async editData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        const model: any = this.tmpPermissionModel;
        model.updateData = parseTime(new Date());
        const { data } = await savePermission(model);
        this.$message({
          message: "操作成功",
          type: "success",
        });
        this.dialogFormVisible = false;

        this.tmpPermissionModel = cloneDeep(this.defaultPermissionValue);
        this.loadSysPermission();
      }
    });
  }
  private rules = {
    name: [
      {
        required: true,
        message: "不能为空",
        trigger: "blur",
      },
      { min: 3, max: 64, message: "长度在3到64个字符", trigger: "blur" },
    ],
    url: [
      { required: true, message: "不能为空", trigger: "blur" },
      { min: 3, max: 128, message: "长度在3到128个字符", trigger: "blur" },
    ],
    grp: [
      {
        required: true,
        message: "分组名称不能为空",
        trigger: "blur",
      },
      { min: 3, max: 255, message: "长度在3到255个字符", trigger: "blur" },
    ],
  };

  private treeData: Array<any> = [];

  private grpLs: Array<any> = [];

  private async loadSysPermission() {
    const { data } = await sysPermission({});

    //按资源组显示列表
    if (data) {
      let ls = data.sort((a: any, b: any) => {
        let e = a.grp.localeCompare(b.grp);
        if (e != 0) return e;
        return a.id - b.id;
      });

      let ts: Array<any> = [];

      for (let o of ls) {
        let tmps = ts.filter((it) => it.grp == o.grp);
        if (tmps.length == 0) {
          ts.push(o);
          this.grpLs.push(o.grp);
        } else {
          let it = tmps[0];
          it.children = it.children || [];
          it.children.push(o);
        }
      }
      this.treeData = ts;
      console.log(this.grpLs);
    }
  }
}
</script>